package com.youlai.quarkus.system.common.exception;

import com.youlai.quarkus.system.common.result.Result;
import io.netty.util.internal.ThrowableUtil;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * 全局系统异常处理器
 * <p>
 * 调整异常处理的HTTP状态码，丰富异常处理类型
 *
 * @author Gadfly
 * @since 2020-02-25 13:54
 **/
@Slf4j
//@Provider
public class GlobalExceptionHandler implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable exception) {
        log.error(ThrowableUtil.stackTraceToString(exception));
        // 业务异常
        if (exception.getClass().isAssignableFrom(BusinessException.class)) {
            BusinessException e = (BusinessException) exception;
            return Response.ok()
                    .entity(Result.result(e.getCode(), e.getMessage(), e.data))
                    .type(MediaType.APPLICATION_JSON_TYPE)
                    .build()
                    ;
        }
        return Response.ok()
                .entity(Result.failed())
                .type(MediaType.APPLICATION_JSON_TYPE)
                .build();
    }
}
